import express from "express";
import db from "./../libs/DBhelper/index";
import fs from "fs";

const apiroute = express.Router(); 
apiroute.get("/login", (request, response, next) => {
    response.end("login,我是真的login");


})
apiroute.post("/reg", (request, response, next) => {
    let sql = "INSERT INTO userinfo (u_name,u_pwd)VALUES (?,?) ;";
    let params = [request.body.uname, request.body.upwd]
    db.exec(sql, params, (err, result, fields) => {

        if (err) {
            response.json({
                msg: "执行sql异常",
                err: err.message,
                status: -1
            });
            return;
        }
        if (result.affectedRows == 1) {
            response.json({
                msg: "注册成功",
                status: 1
            });
        } else {
            response.json({
                msg: "注册失败",
                status: -2
            });
        }

    })
})
apiroute.post("/login", (request, response, next) => {

    let sql = "SELECT `u_id`,`u_name` FROM `userinfo` WHERE u_name=? AND u_pwd=? ;";
    console.log(2222);
    let params = [request.body.uname,
        request.body.upwd
    ]
    console.log(params);
    db.execSync(sql, params).then((result, fields) => {
        console.log(result, fields);

        if (result.length >= 1) {
            response.json({
                msg: "登录成功",
                status: 101,
                data: result[0]
            });
        } else {
            response.json({
                msg: "登录失败",
                status: -101,
            });
        }
    })
})

apiroute.post("/login2", async (request, response, next) => {

    let sql = "SELECT `u_id`,`u_name` FROM `userinfo` WHERE u_name=? AND u_pwd=? ;";

    let params = [request.body.uname,
        request.body.upwd
    ]
    let result = await db.execSync(sql, params);

    var resultJSON = {
        msg: "登录失败",
        status: -201
    }
    if (result.length >= 1) {
        resultJSON["msg"] = "登录成功";
        resultJSON["status"] = 201;
        resultJSON["data"] = result[0]
    }
    response.json(resultJSON)

})

apiroute.get("/goods", (request, response, next) => {

    let params = request.query;
    var goodsStr = fs.readFileSync("./data/goods.json");
    var goodsArr = JSON.parse(goodsStr);
    if (params.gid != undefined) {
        var newArr = goodsArr.filter((el, index) => {
            return el.gid == params.gid
        });

        response.json(newArr)

    } else {

        response.json(goodsArr)
    }

})
//加入购物车
apiroute.post("/addcart", async (request, response, next) => {


    let sqlQuery = " SELECT * FROM `carts` WHERE u_id=? AND c_name=? ;";
    let paramsQuery = [
        request.body.uid,
        request.body.gname,
    ]
    console.log(paramsQuery)
    //先查询,如果有,就做修改,如果没有做插入
    var resultQuery = await db.execSync(sqlQuery, paramsQuery)
    if (resultQuery.length >= 1) { //已经购买了
        let sqlUpdate = "UPDATE carts SET c_num=c_num+? , c_total= c_num*c_price WHERE u_id=? AND c_name=? ;";

        let pramasUpdate = [
            request.body.num,
            request.body.uid,
            request.body.gname
        ]

        var resultUpdate = await db.execSync(sqlUpdate, pramasUpdate);

        response.json({
            msg: "加入购车成功u",
            status: 1
        });

    } else {
        // {gid: 1, gname: "95新苹果6s 64G", gprice: 1049, gimgs1: "./images/1_1.jpg", num: 1}
        let sqlInsert = "INSERT INTO carts (c_name,c_price,c_num,c_total,c_img,u_id)VALUES (?,?,?,?,?,?);";
        let pramasInert = [
            request.body.gname,
            request.body.gprice,
            request.body.num,
            request.body.gprice * request.body.num,
            request.body.gimgs1,
            // request.session["users"].u_id
            request.body.uid
        ]
        const result = await db.execSync(sqlInsert, pramasInert);
        response.json({
            msg: "加入购车成功i",
            status: 1
        });
    }

})


apiroute.get("/carts", async (request, response, next) => {

    var query = 'SELECT *FROM `carts` WHERE u_id=?;';
    var parmas = [
        request.query.uid
    ]
    
    var result = await db.execSync(query, parmas);
    response.json(result);
})


apiroute.post("/changecarts", async function (request, response, next) {
    let sql = "UPDATE carts SET c_num=? , c_total= c_num*c_price WHERE c_id=?";

    let params = [request.body.num, request.body.cid];
    var result = await db.execSync(sql, params);

    response.json({
        msg: "查询成功",
        status: 1,
        data: result
    })
})

//删除购物车
apiroute.post("/delete", async (request, response, next) => {
    let sql = "DELETE FROM carts WHERE c_id= ? ;";
    let params = [request.body.cid];

    var result = await db.execSync(sql, params);
    if (result.affectedRows == 1) {

        response.json({
            msg: "删除成功",
            status: 1
        })
    } else {
        response.json({
            msg: "删除失败",
            status: -1
        })
    }

})
apiroute.get("/checkUname", (request, response, next) => {
    var userObj = request.query;
    let sql = "SELECT * FROM userinfo WHERE u_name=? ;";
    let parmas = [userObj.uname];
    db.exec(sql, parmas, (err, result, fields) => {
        if (err) {
            response.json({
                msg: "执行sql语句错误",
                err: err.message
            }); 
            return;
        }
        if (result.length >= 1) {
            response.end("false"); 
        } else {
            response.end("true"); 
        }
    })

})
//退出登录
// apiroute.get("/logout",async (request,response,next)=>{
//     request.session["users"] =null;
//     response.clearCookie();
//     response.json({
//         msg:"退出成功",
//         status:1
//     })
// })

module.exports = apiroute